package com.hh.TreeQuestions;

import java.util.Stack;

/**
 * @author hanghao
 * @date 2023/8/3 14:52
 * 二叉搜索树中第K小的元素
 * middle
 */
public class No230 {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                root = stack.pop();
                k--;
                if (k == 0) {
                    break;
                }
                root = root.right;
            }
        }
        return root.val;
    }
}
